/**
 * 全局变量管理器;
 */
import {BaseScene} from './scenes/BaseScene';
import {global} from 'Main';
export class GlobalVariables {
    public canvas: HTMLCanvasElement;
    public engine: BABYLON.Engine;
    public pointerLockListener: boolean;        //鼠标锁定是否已经开启            
    public sceneOnRender: SCENE;                //正在被渲染的场景名称
    public scenesInitialed: BaseScene[];    //场景容器，未被初始化的场景设置为null


    static lock = (e) => {  //鼠标锁定
        global.canvas.requestPointerLock();
    };

    constructor(canvasName = "renderCanvas"){
        this.canvas = <HTMLCanvasElement>document.getElementById(canvasName);
        this.engine = this.createDefaultEngine();
        this.sceneOnRender = null;
        this.pointerLockListener = false;
        this.scenesInitialed = new Array<BaseScene>(SCENE.Z_END_SYMBOL);
        this.scenesInitialed.fill(null);    //场景初始化为null

    }

    /**
     * 创建默认的引擎;
     */
    public createDefaultEngine(): BABYLON.Engine {
        return new BABYLON.Engine(this.canvas, true, { preserveDrawingBuffer: true, stencil: true });
    };

    /**
     * 检查初始化是否成功，不成功会抛出异常;
     */
    public checkIfSuccess(): void{
        if(this.canvas == null){
            throw "canvas is not found.";
        }
        if(this.engine == null){
            throw "engine initialized failed.";
        }
    }

    /**
     * 添加预加载的场景;
     * @param scene 实例化的场景;
     * @param sceneType  已注册的场景类型;
     * 
     */
    public addPrestrainedScene(scene:BaseScene, sceneType:SCENE): void {
        this.scenesInitialed[sceneType] = scene;
    }

    /**
     * 请求场景渲染，如果请求的场景未初始化则抛出异常;
     * @param sceneType 已注册的场景类型;
     */
    public askForRender(sceneType:SCENE): void {
        if(this.scenesInitialed[sceneType] == null){
            throw "scene is not initialized.";
        }

        global.sceneOnRender = sceneType;
    }
    
    /**
     * 为canvas添加鼠标锁定;
     * 
     */
    public addMouseClickLockListner() {
        //触发鼠标锁定
        if(global.pointerLockListener){
            return;
        }
        global.canvas.addEventListener('click', GlobalVariables.lock);
        global.pointerLockListener = true;
    }
    
    /**
     * 移除鼠标锁定;
     */
    public removeMouseClickLockListner() {
        if(!global.pointerLockListener){
            return;
        }
        global.canvas.removeEventListener('click', GlobalVariables.lock);
        document.exitPointerLock();
        global.pointerLockListener = false;
    }
}